import React, { useState, useEffect, useRef } from 'react';
import useStore from '../../components/useStore';
import { Button, Card, Col, Empty, Form, notification, Row, Input, Pagination } from 'antd';
import { SearchOutlined, FileExcelOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';
import request from '../../untils/request'

// 通用请求函数封装
const fetchData = async (url, data, showSuccess = true) => {
  try {
    const result = await request(url, {
      method: "POST",
      mode: 'cors',
      body: data
    });
    if (result.code === 200) {
      if (showSuccess && result.msg) {
        notification.success({ message: result.msg });
      }
      return result;
    } else {
      notification.error({ message: result.msg || "未知错误" });
      return null;
    }
  } catch (error) {
    notification.error({ message: "网络请求异常" });
    return null;
  }
};

// 导出Excel功能
const exportToExcel = (data, filename = '产品出货单列表') => {
  const columns = [
    { key: 'shipment_order_id', title: '出货单号' },
    { key: 'delivery_address', title: '送货地址' },
    { key: 'product_part_number', title: '产品料号' },
    { key: 'product_name', title: '产品名称' },
    { key: 'specification', title: '产品规格' },
    { key: 'shipment_number', title: '出货数量' },
    { key: 'shipment_date', title: '出货日期' },
    { key: 'shipment_customer', title: '出货客户' },
    { key: 'sales_order_id', title: '销售单号' },
    { key: 'create_time', title: '创建时间' },
  ];
  
  const formattedData = data.map(item => {
    const formattedItem = {};
    columns.forEach(col => {
      formattedItem[col.title] = item[col.key] || '';
    });
    return formattedItem;
  });
  
  const worksheet = XLSX.utils.json_to_sheet(formattedData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '产品出货单');
  XLSX.writeFile(workbook, `${filename}.xlsx`);
};

const SearchProductDelivery = () => {
  const { collapsed, setnowroute } = useStore();
  const [productShipmentList, setproductShipmentList] = useState([]);
  const [searchFrom] = Form.useForm();
  const [currentPage, setcurrentPage] = useState(1);
  const [total, settotal] = useState(0);
  const [loading, setLoading] = useState(false);
  
  // 同步表头和内容区域的滚动
  const headerRef = useRef(null);
  const handleScroll = (e) => {
    if (headerRef.current) {
      headerRef.current.scrollLeft = e.target.scrollLeft;
    }
  };

  // 搜索功能
  const search = async () => {
    const condition = await searchFrom.getFieldsValue();
    const result = await fetchData("/admin/productDelivery/searchProductDelivery", {
      condition,
      pageSize: 10,
      offset: (currentPage - 1) * 10
    }, true);
    
    if (result) {
      setproductShipmentList(result.data);
      settotal(result.total);
    }
  };

  // 导出Excel
  const exportExcel = async () => {
    setLoading(true);
    notification.info({ message: "正在准备导出数据，请稍候..." });
    
    try {
      const condition = await searchFrom.getFieldsValue();
      const result = await fetchData("/admin/productDelivery/searchProductDelivery", {
        condition,
        pageSize: total,
        offset: 0
      }, false);
      
      if (result && result.data && result.data.length > 0) {
        exportToExcel(result.data, '产品出货单查询结果');
        notification.success({ message: `成功导出 ${result.data.length} 条数据` });
      } else {
        notification.warning({ message: "没有可导出的数据" });
      }
    } catch (error) {
      notification.error({ message: "导出失败，请重试" });
    } finally {
      setLoading(false);
    }
  };

  // 查看详情
  const toProductShipmentDetail = (id) => {
    setnowroute({ 
      route: `/ship/productDelivery/showProductDelivery?id=${id}`, 
      title: "查看产品出货单" 
    });
  };

  // 分页切换
  const changePage = async (e) => {
    setcurrentPage(e);
    const condition = await searchFrom.getFieldsValue();
    const result = await fetchData("/admin/productDelivery/searchProductDelivery", {
      condition,
      pageSize: 10,
      offset: (e - 1) * 10
    }, false);
    
    if (result) {
      setproductShipmentList(result.data);
    }
  };

  // 前往修改
  const toUpdate = (id) => {
    setnowroute({ route: `/ship/productDelivery/updateProductDelivery?id=${id}`, title: "修改产品出货单" });
  };

  // 初始加载
  useEffect(() => {
    const initSearch = async () => {
      const condition = await searchFrom.getFieldsValue();
      const result = await fetchData("/admin/productDelivery/searchProductDelivery", {
        condition,
        pageSize: 10,
        offset: 0
      }, false);
      
      if (result) {
        setproductShipmentList(result.data);
        settotal(result.total);
      }
    };
    initSearch();
  }, []);

  return (
    <div style={{
      height: "94%",
      backgroundColor: `#F1F1F1`,
      right: "1%",
      top: "4vh",
      overflow: "hidden",
      width: collapsed ? "94%" : "84%",
      position: "absolute",
      color: "white",
      fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem",
          position: "relative",
          width: "96%",
          marginLeft: "2%",
          display: "flex",
          textIndent: "1rem",
          justifyContent: "flex-start",
          alignContent: "flex-start",
          flexWrap: "wrap"
        }}>
          {/* 搜索区域 */}
          <Card 
            title="请输入条件进行查询" 
            style={{ width: "100%", marginTop: "2vh" }}
            extra={
              <>
                <Button 
                  icon={<FileExcelOutlined />} 
                  onClick={exportExcel} 
                  loading={loading}
                  style={{ marginRight: 8 }}
                >
                  导出Excel
                </Button>
                <Button onClick={() => setnowroute({
                  route: "/ship/productDelivery/productDeliveryUploadOrder",
                  title: "上传产品出货单"
                })}>
                  新增
                </Button>
              </>
            }
          >
            <Form form={searchFrom}>
              <Row gutter={24}>
                <Col span={12}>
                  <Form.Item
                    label="出货单号"
                    name="shipment_order_id"
                    getValueFromEvent={(e) => e.target.value.trim() || null}
                  >
                    <Input placeholder='请输入出货单号' maxLength={50} showCount />
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="送货地址"
                    name="delivery_address"
                    getValueFromEvent={(e) => e.target.value.trim() || null}
                  >
                    <Input placeholder='请输入送货地址' maxLength={100} showCount />
                  </Form.Item>
                </Col>
              </Row>
            </Form>
            <Button icon={<SearchOutlined />} onClick={search}>搜索</Button>
          </Card>

          {/* 列表区域 */}
          <Card
            style={{ width: "100%", marginTop: "2vh" }}
            title="产品出货单列表"
          >
            {productShipmentList.length === 0 ? (
              <Empty />
            ) : (
              <div style={{ width: "100%", overflow: "hidden", border: '1px solid #e8e8e8', borderRadius: '4px' }}>
                {/* 表头区域 */}
                <div 
                  ref={headerRef}
                  style={{ 
                    width: "100%",
                    overflowX: "auto",
                    ...styles.hideScrollbar
                  }}
                >
                  <Row style={{ width: "100%", display: 'flex' }}>
                    <div style={{...styles.headerCell, width: '10%'}}>
                      <div style={{ padding: '8px' }}>序号</div>
                    </div>
                    <div style={{...styles.headerCell, width: '20%'}}>
                      <div style={{ padding: '8px' }}>出货单号</div>
                    </div>
                    <div style={{...styles.headerCell, width: '25%'}}>
                      <div style={{ padding: '8px' }}>送货地址</div>
                    </div>
                    <div style={{...styles.headerCell, width: '20%'}}>
                      <div style={{ padding: '8px' }}>出货日期</div>
                    </div>
                    <div style={{...styles.headerCell, width: '25%'}}>
                      <div style={{ padding: '8px' }}>操作</div>
                    </div>
                  </Row>
                </div>

                {/* 内容区域 */}
                <div 
                  style={{ 
                    height: "40vh", 
                    overflowY: "auto", 
                    overflowX: "auto",
                    ...styles.thinScrollbar
                  }}
                  onScroll={handleScroll}
                >
                  {productShipmentList.map((item, rowIndex) => (
                    <Row 
                      key={item.id}
                      style={{
                        width: "100%",
                        display: 'flex',
                        backgroundColor: rowIndex % 2 === 0 ? '#f9f9f9' : 'white'
                      }}
                    >
                      <div style={{...styles.dataCell, width: '10%'}}>
                        {rowIndex + 1}
                      </div>
                      <div style={{...styles.dataCell, width: '20%'}}>
                        {item.shipment_order_id}
                      </div>
                      <div style={{
                        ...styles.dataCell, 
                        width: '25%',
                        whiteSpace: 'nowrap',
                        overflow: 'hidden',
                        textOverflow: 'ellipsis'
                      }}>
                        {item.delivery_address}
                      </div>
                      <div style={{...styles.dataCell, width: '20%'}}>
                        {item.shipment_date || '-'}
                      </div>
                      <div style={{...styles.dataCell, width: '25%'}}>
                        {/* 修改为无下划线的蓝色链接样式按钮，并调整文本 */}
                        <Button 
                          size='small' 
                          onClick={() => toProductShipmentDetail(item.id)}
                          type="text" 
                          style={styles.linkButton}
                        >
                          查看
                        </Button>
                        <Button 
                          size='small' 
                          onClick={() => toUpdate(item.id)}
                          type="text" 
                          style={styles.linkButton}
                        >
                          修改
                        </Button>
                      </div>
                    </Row>
                  ))}
                </div>

                {/* 分页 */}
                <div style={{ marginTop: 16, textAlign: 'right', padding: '12px' }}>
                  <span style={{ marginRight: 16 }}>共 {total} 条记录</span>
                  <Pagination
                    current={currentPage}
                    onChange={changePage}
                    total={total}
                  />
                </div>
              </div>
            )}
          </Card>
        </div>
      </div>
    </div>
  );
};

// 样式定义
const styles = {
  kshcontainer: {
    width: "98%",
    height: "95%",
    position: "absolute",
    top: "3%",
    left: "1%",
    backgroundColor: "white",
    color: "black",
    borderRadius: "10px",
    boxSizing: 'border-box',
    overflowY: 'scroll'
  },
  // 表头单元格样式
  headerCell: {
    flex: 'none',
    backgroundColor: '#40a9ff',
    color: 'white',
    borderRight: '1px solid #fff',
    borderBottom: '1px solid #ccc',
    boxSizing: 'border-box',
    minHeight: '42px',
  },
  // 数据单元格样式
  dataCell: {
    flex: 'none',
    padding: '8px',
    borderRight: '1px solid #e8e8e8',
    borderBottom: '1px solid #e8e8e8',
    boxSizing: 'border-box',
    minHeight: '42px',
  },
  // 链接样式按钮（无下划线）
  linkButton: {
    color: '#1890ff',  // 蓝色
    padding: '4px 8px',
    marginRight: '12px',
    // 移除下划线
    '&:hover': {
      color: '#40a9ff',  // 悬停时颜色变浅
      textDecoration: 'none',  // 确保无下划线
    }
  },
  // 窄滚动条样式
  thinScrollbar: {
    scrollbarWidth: 'thin',
    scrollbarColor: '#ccc transparent',
  },
  // 隐藏滚动条但保留功能
  hideScrollbar: {
    scrollbarWidth: 'none',
    '-ms-overflow-style': 'none',
  }
};

// 添加全局样式以支持WebKit浏览器的窄滚动条
const style = document.createElement('style');
style.textContent = `
  .thin-scrollbar::-webkit-scrollbar {
    width: 4px;
    height: 4px;
  }
  .thin-scrollbar::-webkit-scrollbar-track {
    background: transparent;
  }
  .thin-scrollbar::-webkit-scrollbar-thumb {
    background-color: #ccc;
    border-radius: 2px;
  }
  .thin-scrollbar::-webkit-scrollbar-thumb:hover {
    background-color: #999;
  }
  .hide-scrollbar::-webkit-scrollbar {
    display: none;
  }
  .ant-row {
    white-space: nowrap;
    box-sizing: border-box;
  }
  .ant-btn-text:hover {
    background-color: transparent !important;
    text-decoration: none !important;
  }
`;
document.head.appendChild(style);

export default SearchProductDelivery;
    